package org.idea.spring.framework.event;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.*;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * @Author linhao
 * @Date created in 10:29 上午 2021/5/30
 */
public class ApplicationEventPublisherDemo2 implements ApplicationContextAware, ApplicationEventPublisherAware {

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    public static void main(String[] args) {
        AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext();
        annotationConfigApplicationContext.register(ApplicationEventPublisherDemo2.class);
        annotationConfigApplicationContext.register(MsgEventListener.class);
//        annotationConfigApplicationContext.addApplicationListener(new ApplicationListener<MsgEvent>() {
//            @Override
//            public void onApplicationEvent(MsgEvent event) {
//                System.out.println("event is ");
//            }
//        });
        annotationConfigApplicationContext.refresh();
        annotationConfigApplicationContext.close();
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        applicationContext.publishEvent(new MsgEvent("applicationContext aware"));
    }

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        applicationEventPublisher.publishEvent(new MsgEvent("applicationEventPublisher aware"));
    }

    static class MsgEventListener implements ApplicationListener<MsgEvent> {

        @Override
        public void onApplicationEvent(MsgEvent event) {
            System.out.println("event is "+event);
        }
    }

    static class MsgEvent extends ApplicationEvent {

        /**
         * Create a new {@code ApplicationEvent}.
         *
         * @param source the object on which the event initially occurred or with
         *               which the event is associated (never {@code null})
         */
        public MsgEvent(Object source) {
            super(source);
        }
    }
}
